package com.sxf.auth.login.service;


import cn.hutool.json.JSONUtil;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.sxf.auth.login.vo.SmsVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @description: TODO
 * @Author Leo
 * @date 2025/4/2320:54
 */
@Component
public class AliYunSmsTool {
    private Logger logger = LoggerFactory.getLogger(getClass().getName());

    @Value("${sxf.sms.aliyun.appKey:###}")
    private String appKey;
    @Value("${sxf.sms.aliyun.appSecret:###}")
    private String appSecret;

    private Client client;

    public Client getClient(){
        if(this.client == null){
            synchronized (AliYunSmsTool.class){
                if(this.client == null){
                    try {
                        Config config = new Config();
                        config.setAccessKeyId("LTAI5tBsdeQD6j1SHBkkLanA");
                        config.setAccessKeySecret("6zzQ7G02UrJXBUq1JUHqSpqITMgdXs");
                        config.setEndpoint("dysmsapi.aliyuncs.com");
                        return new Client(config);
                    } catch (Exception e) {
                        logger.error("create SMS client error {}",e.getMessage());
                        e.printStackTrace();
                    }
                }
            }
        }
        return this.client;
    }

    public Boolean sendSms(SmsVo vo){
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(vo.getMobile())
                .setSignName("天津凯芾医药科技")
                .setTemplateCode(vo.getTemplateId())
                .setTemplateParam("{\"code\":\"" + vo.getSmsCode() +"\"}");
        // 获取响应对象
        try {
            SendSmsResponse sendSmsResponse = getClient().sendSms(sendSmsRequest);
            if("OK".equals(sendSmsResponse.getBody().getCode())){
                logger.info("短信发送成功-{}",vo.getMobile());
                return Boolean.TRUE;
            }else{
                logger.error("短信发送失败-{}",JSONUtil.toJsonStr(sendSmsResponse.getBody()));
                return Boolean.FALSE;
            }
        } catch (Exception e) {
            logger.error("send SMS error : {}",e.getMessage());
            throw new RuntimeException("短信发送失败");
        }
    }

    public static void main(String[] args) {
        AliYunSmsTool aliYunSmsTool = new AliYunSmsTool();
        SmsVo vo = new SmsVo();
        vo.setMobile("15222891706");
        vo.setTemplateId("SMS_317160006");
        vo.setSmsCode("123456");
        aliYunSmsTool.sendSms(vo);
    }

}
